package com.zonski.jbots.game.resources;

import java.util.Vector;

import com.zonski.jbots.engine.*;

import com.zonski.jbots.game.JBotsConstants;
import com.zonski.jbots.game.EntityHelper;

public class CometMaker extends IntermittentResource
{
    private static final int DEFAULT_UPDATES_BETWEEN_COMETS = 3;
    private static final int DEFAULT_COST = 3;

    private QuickVector currentComets;
    private int maxComets;

    public CometMaker(int maxComets)
    {
        super(DEFAULT_UPDATES_BETWEEN_COMETS);
        this.maxComets = maxComets;
        this.currentComets = new QuickVector(maxComets);
    }

    public int getCurrentChargeCost()
    {
        return DEFAULT_COST;
    }

    protected Entity create(Engine engine)
        throws Exception
    {
        Entity comet;
        boolean occupied = EntityHelper.isOccupied(this.getOwner(), engine, JBotsConstants.EGG_ID);
        if(!occupied)
        {
            EntityFactory entityFactory = engine.getEntityFactory();
            comet = entityFactory.createEntity(JBotsConstants.COMET);
            comet.direction = this.getOwner().direction;
            //comet.bounds.setCentre(this.getOwner().bounds);
            EntityHelper.centreAtClosestTile(comet.bounds,
                    this.getOwner().bounds, engine.getRoom());
            comet.layerId = this.getOwner().layerId;

            // ensure that there's not too many comets
            if(this.currentComets.size() >= maxComets-1)
            {
                // check that at least one is dead or kill off the
                // first one
                for(int i=this.currentComets.size(); i>0; )
                {
                    i--;
                    Entity found = (Entity)this.currentComets.elementAt(i);
                    if(found.isRemovable() || found.getMode() != Modes.NONE)
                    {
                        this.currentComets.removeElementAt(i);
                    }
                }
                while(this.currentComets.size() > maxComets-1)
                {
                    Entity found = (Entity)this.currentComets.elementAt(0);
                    found.setRemovable(true);
                    this.currentComets.removeElementAt(0);
                }
            }
            this.currentComets.addElement(comet);
        }else{
            comet = null;
        }
        return comet;
    }

    public Resource copy()
    {
        CometMaker cometMaker = new CometMaker(this.maxComets);
        cometMaker.setKillOwner(this.getKillOwner());
        cometMaker.setUpdatesBetweenCreations(getUpdatesBetweenCreations());
        return cometMaker;
    }
}
